<template>
  <div>
    <div style="text-align:left; margin-bottom: 20px; max-width: 700px; margin-left: auto; margin-right: auto;">
      <label style="margin-right:6px;">病区：</label>
      <select v-model="query.wardAreaCode" class="select-beauty">
        <option value="">全部病区</option>
        <option v-for="item in wardAreaList" :key="item.wardAreaCode" :value="item.wardAreaCode">
          {{ item.name }}
        </option>
      </select>
      <label style="margin-left:18px;margin-right:6px;">床位：</label>
      <select v-model="query.bedCode" class="select-beauty">
        <option value="">全部床位</option>
        <option v-for="bed in bedOptions" :key="bed" :value="bed">{{ bed }}</option>
      </select>
      <button @click="getPatients" class="btn-beauty" style="margin-left: 10px;">查询</button>
    </div>
    <h2 style="text-align:center;">请选择床位</h2>
    <div class="bed-list">
      <div v-for="bed in beds" :key="bed.bedCode" :class="['bed-card', { empty: !bed.patient }]"
        @click="bed.patient && openDialog(bed.patient)" style="cursor: pointer;">
        <div v-if="bed.patient">
          <div>{{ bed.bedCode }} {{ bed.patient.name }}</div>
        </div>
        <div v-else>
          <div>{{ bed.bedCode }} 暂无</div>
        </div>
      </div>
    </div>
    <template v-if="showDialog">
      <div class="dialog-mask">
        <div class="dialog-content">
          <h2>条码打印</h2>
          <button @click="barcodeType = 'barcode'">患者条形码</button>
          <button @click="barcodeType = 'qrcode'">患者二维码</button>
          <button @click="barcodeType = 'urine'">小便二维码</button>
          <button @click="barcodeType = 'stool'">大便二维码</button>
          <div v-if="barcodeType === 'barcode'" style="margin:20px 0;">
            <svg id="barcode"></svg>
          </div>
          <div v-if="barcodeType === 'qrcode'" style="margin:20px 0;">
            <QRCodeVue :value="qrText" :size="120" />
          </div>
          <div v-if="barcodeType === 'urine'" style="margin:20px 0;">
            <div
              style="width:120px;height:120px;border:1px dashed #888;margin:0 auto;display:flex;align-items:center;justify-content:center;">
              小便二维码</div>
          </div>
          <div v-if="barcodeType === 'stool'" style="margin:20px 0;">
            <div
              style="width:120px;height:120px;border:1px dashed #888;margin:0 auto;display:flex;align-items:center;justify-content:center;">
              大便二维码</div>
          </div>
          <div style="margin-top:20px;">
            <button @click="closeDialog">关闭</button>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

<script setup>
import { onMounted, ref, computed, watch, nextTick } from 'vue'
import htpp from "@/api/http";
import QRCodeVue from 'qrcode.vue'

const query = ref({
  wardAreaCode: '',
  bedCode: ''
})

const wardAreaList = ref([])

const getWardAreaList = () => {
  htpp.get("/api/BasicController/GetWardAreas").then(res => {
    wardAreaList.value = res.data || []
  })
}

const patientList = ref([])

const totalBeds = 9

const beds = computed(() => {
  return Array.from({ length: totalBeds }, (_, i) => {
    const bedCode = `${i + 1}床`
    const patient = patientList.value.find(p => p.bedCode === bedCode)
    return { bedCode, patient }
  })
})

const getPatients = () => {
  htpp.post("/api/BasicController/GetPatientList", query.value).then(res => {
    patientList.value.length = 0
    patientList.value = res.data || []
  })
}

const showDialog = ref(false)
const selectedPatient = ref(null)
const barcodeType = ref('') // 'barcode' or 'qrcode' or 'urine' or 'stool'

const openDialog = (patient) => {
  selectedPatient.value = patient
  showDialog.value = true
  barcodeType.value = ''
}
const closeDialog = () => {
  showDialog.value = false
  selectedPatient.value = null
  barcodeType.value = ''
}

const qrText = computed(() => {
  if (!selectedPatient.value) return ''
  const p = selectedPatient.value
  // 只排除id字段，其余全部显示
  const fields = [
    { label: '患者编号', value: p.patientCode },
    { label: '姓名', value: p.name },
    { label: '性别', value: p.sex === 1 ? '男' : p.sex === 2 ? '女' : '' },
    { label: '年龄', value: p.age },
    { label: '科室', value: p.officeCode },
    { label: '病区', value: p.wardAreaCode },
    { label: '护理单元', value: p.nursingUnit },
    { label: '病房号', value: p.wardCode },
    { label: '床位号', value: p.bedCode },
    { label: '身份证号', value: p.idNo },
    { label: '联系电话', value: p.phone },
    { label: '地址', value: p.address },
    { label: '紧急联系人', value: p.sosName },
    { label: '诊断', value: p.diagnosis }
  ]
  return fields.filter(f => f.value !== undefined && f.value !== null && f.value !== '').map(f => `${f.label}: ${f.value}`).join('\n')
})

watch([barcodeType, selectedPatient], async ([type, patient]) => {
  if (type === 'barcode' && patient) {
    await nextTick()
    const svg = document.getElementById('barcode')
    if (svg) svg.innerHTML = '' // 先清空
    if (window.JsBarcode) {
      window.JsBarcode(svg, patient.patientCode, {
        format: "CODE128",
        width: 2,
        height: 60,
        displayValue: true
      })
    } else {
      // 兼容import JsBarcode from 'jsbarcode'
      try {
        const JsBarcode = (await import('jsbarcode')).default
        JsBarcode(svg, patient.patientCode, {
          format: "CODE128",
          width: 2,
          height: 60,
          displayValue: true
        })
      } catch (e) {
        // 可选：错误提示
      }
    }
  }
})

const bedOptions = [
  '1床', '2床', '3床', '4床', '5床', '6床'
]

onMounted(() => {
  getWardAreaList()
  getPatients()
})
</script>

<style scoped>
.bed-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  max-width: 700px;
  margin: 40px auto 0;
}

.bed-card {
  width: 180px;
  height: 60px;
  margin: 20px 0;
  border: 1px solid #aaa;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 16px;
  background: #fff;
  transition: background 0.2s;
}

.bed-card.empty {
  background: #aaa;
  color: #fff;
}

.dialog-mask {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.2);
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.dialog-content {
  background: #7ffcff;
  padding: 30px 40px;
  border-radius: 10px;
  min-width: 300px;
  text-align: center;
}

.dialog-content button {
  margin: 10px 0;
  width: 160px;
  height: 36px;
  font-size: 16px;
}

.select-beauty {
  padding: 6px 16px;
  border: 1px solid #7fdcff;
  border-radius: 6px;
  font-size: 15px;
  outline: none;
  margin-bottom: 0;
}

.btn-beauty {
  padding: 6px 24px;
  background: #19bfff;
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 15px;
  cursor: pointer;
  transition: background 0.2s;
}

.btn-beauty:hover {
  background: #0fa0d6;
}
</style>
